<template>
    <div>
        <el-alert title="注意: 只允许为第三级分类设置相关参数!" :closable="false" type="warning" show-icon> </el-alert>
        <el-row class="cat_opt">
            <span>选择商品分类: &nbsp;</span>
            <el-cascader v-model="selectdCateKeys" :options="cateList" :props="cateProps" @change="handleChange">
            </el-cascader>
        </el-row>
        <el-tabs v-model="activeName">
            <el-tab-pane label="动态参数" name="many">
                <el-button type="primary" @click="showAddDialog" size="small" class="addBtn">添加参数</el-button>
                <el-table :data="manyTableData" border stripe row-key="attr_id" :expand-row-keys="expands">
                    <el-table-column type="expand">
                        <template v-slot="scope">
                            <el-tag closable v-for="(item, index) in scope.row.attr_vals" :key="index"
                                @close="handleClosed(index, scope.row)"> {{ item }}</el-tag>
                            <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue"
                                ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm(scope.row)"
                                @blur="handleInputConfirm(scope.row)">
                            </el-input>
                            <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New
                                Tag</el-button>
                        </template>
                    </el-table-column>
                    <el-table-column type="index" label="#" align="center" />
                    <el-table-column label="参数名称" prop="attr_name" align="center" />
                    <el-table-column label="操作" align="center">
                        <template v-slot="scope">
                            <el-button type="primary" @click="showEditDialog(scope.row)" :icon="EditPen" size="small">编辑
                            </el-button>
                            <el-button type="danger" @click="removeParams(scope.row.attr_id)" :icon="Delete"
                                size="small">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-tab-pane>
            <el-tab-pane label="静态属性" name="only">
                <el-button type="primary" @click="showAddDialog" size="small" class="addBtn">添加属性</el-button>
                <el-table :data="onlyTableData" border stripe row-key="attr_id" :expand-row-keys="expands">
                    <el-table-column type="expand">
                        <template v-slot="scope">
                            <el-tag closable v-for="(item, index) in scope.row.attr_vals" :key="index"
                                @close="handleClosed(index, scope.row)"> {{ item }}</el-tag>
                            <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue"
                                ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm(scope.row)"
                                @blur="handleInputConfirm(scope.row)">
                            </el-input>
                            <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New
                                Tag</el-button>
                        </template>
                    </el-table-column>
                    <el-table-column type="index" label="#" align="center" />
                    <el-table-column label="属性名称" prop="attr_name" align="center" />
                    <el-table-column label="操作" align="center">
                        <template v-slot="scope">
                            <el-button type="primary" @click="showEditDialog(scope.row)" :icon="EditPen" size="small">编辑
                            </el-button>
                            <el-button type="danger" @click="removeParams(scope.row.attr_id)" :icon="Delete"
                                size="small">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-tab-pane>
        </el-tabs>
        <el-dialog :title="'添加' + titleText" v-model="addDialogVisible" width="50%" @close="addFormRef.resetFields()">
            <el-form :model="formData" :rules="rules" ref="addFormRef" label-width="20%">
                <el-form-item :label="titleText" prop="attr_name">
                    <el-input v-model="formData.attr_name" style="width: 80%"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="addDialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="addParams(addFormRef)">确 定</el-button>
                </span>
            </template>
        </el-dialog>
        <el-dialog :title="'编辑' + titleText" v-model="editDialogVisible" width="50%" @close="formData.attr_name=''">
            <el-form :model="formData" :rules="rules" ref="editFormRef" label-width="20%">
                <el-form-item :label="titleText" prop="attr_name">
                    <el-input v-model="formData.attr_name" style="width: 80%"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="editDialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="editParams(editFormRef)">确 定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>
<script setup>
    import {
        ElRow, ElCascader, ElTag,
        ElInput, ElButton,
        ElTable, ElTableColumn,
        ElDialog, ElMessage, ElAlert, ElMessageBox,
        ElForm, ElFormItem,
        ElTabs, ElTabPane
    } from "element-plus"
    import {
        EditPen,
        Delete
    } from '@element-plus/icons-vue'
    import {
        getCategories,
        getCateAttrs,
        postCateAttrs,
        putCateAttrs,
        deleteCateAttrs
    } from "@/tools/ajax.js"
    import { reactive, ref, computed } from "vue"
    import { useRules } from "@/tools/utils"
    const cateList = reactive([])
    const cateProps = {   
        expandTrigger: 'hover',
        label: 'cat_name',
        value: 'cat_id',
        children: 'children'
    }
    getCategories().then(res => { 
        if (res.meta.status != 200) return ElMessage.error(res.meta.msg)
        cateList.push(...res.data)
    })
    const selectdCateKeys = ref([]); 
    const manyTableData = reactive([]) 
    const onlyTableData = reactive([])
    async function handleChange() { 
        console.log(selectdCateKeys);
        const res = await getCateAttrs({
            id: selectdCateKeys.value[selectdCateKeys.value.length - 1],
            sel: "many",
        })
        console.log(res);
        if (res.meta.status !== 200) return ElMessage.error('获取此分类动态参数失败!')
        res.data.forEach(item => {
            if (item.attr_vals.length === 0) {
                item.attr_vals = []
            } else {
                item.attr_vals = item.attr_vals.split(' ')
            }
        })
        console.log(res.data)
        manyTableData.splice(0)
        manyTableData.push(...res.data)
        const res2 = await getCateAttrs({
            id: selectdCateKeys.value[selectdCateKeys.value.length - 1], 
            sel: "only",
        })
        if (res2.meta.status !== 200) return ElMessage.error('获取此分类静态属性失败!')
        res2.data.forEach(item => {
            if (item.attr_vals.length === 0) {
                item.attr_vals = []
            } else {
                item.attr_vals = item.attr_vals.split(' ')
            }
        })
        console.log(res2.data)
        onlyTableData.splice(0)
        onlyTableData.push(...res2.data)
    }
    const addDialogVisible = ref(false)
    const activeName = ref("many") 
    const addFormRef = reactive({}) 
    const formData = reactive({}) 
    const titleText = computed(() => {
        if (activeName.value == "many") return "动态参数"
        else return "静态属性"
    })
    function showAddDialog() { 
        console.log(selectdCateKeys.value.length);
        if (selectdCateKeys.value.length) addDialogVisible.value = true
        else ElMessage.warning("请先选择分类!");
    }
    const { attrNameRule } = useRules() 
    const rules = {  
        attr_name: attrNameRule
    }
    function addParams(form) { 
        console.log(formData.attr_name, form);
        form.validate(async bool => {
            if (!bool) return ElMessage.error("请正确填写名称!");
            const { meta: res } = await postCateAttrs({
                id: selectdCateKeys.value[selectdCateKeys.value.length - 1], 
                attr_name: formData.attr_name, 
                attr_sel: activeName.value  
            })
            console.log(res);
            if (res.status != 201) return ElMessage.error(res.msg)
            ElMessage.success(res.msg)
            addDialogVisible.value = false
            handleChange()
        })
    }
    const editDialogVisible = ref(false) 
    const editFormRef = reactive({})
    function showEditDialog(data) { 
        formData.attr_name = data.attr_name
        formData.attr_id = data.attr_id
        formData.attr_vals = data.attr_vals
        editDialogVisible.value = true
    }
    function editParams(form) { 
        form.validate(async bool => {
            if (!bool) return ElMessage.error("请正确填写名称!");
            const { meta: res } = await putCateAttrs({
                id: selectdCateKeys.value[selectdCateKeys.value.length - 1], 
                attr_id: formData.attr_id,  
                attr_name: formData.attr_name, 
                attr_sel: activeName.value, 
                attr_vals: formData.attr_vals.join(' ') 
            })
            console.log(res);
            if (res.status != 200) return ElMessage.error(res.msg)
            ElMessage.success(res.msg)
            editDialogVisible.value = false
            handleChange()
        })
    }
    async function removeParams(attr_id) {
        const confirmRusult = await ElMessageBox.confirm('此操作将永久删除此属性或参数, 是否继续?', '永久删除该属性或参数', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).catch(err => err)
        if (confirmRusult !== 'confirm') {
            return ElMessage.info('已经取消了删除')
        }
        const res = await deleteCateAttrs({
            id: selectdCateKeys.value[selectdCateKeys.value.length - 1],
            attr_id  
        })
        if (res.meta.status !== 200) {
            return ElMessage.error(res.meta.msg)
        }
        ElMessage.success(res.meta.msg)
        handleChange()
    }
    const expands = reactive([])
    function showInput(row) {
        console.log('展示输入框',row);
        row.inputVisible = true 
        expands[0] = row.attr_id 
    }
    function handleInputConfirm(row) { 
        console.log(row);
        if (row.inputValue.trim().length === 0) {
            row.inputValue = ''
            row.inputVisible = false
            return
        }
        row.attr_vals.push(row.inputValue.trim())
        row.inputValue = ''
        row.inputVisible = false
        uploadData(row)
    }
    async function uploadData(row){
        const res = await putCateAttrs({
            id: row.cat_id, 
            attr_id: row.attr_id,
            attr_name: row.attr_name, 
            attr_sel: row.attr_sel, 
            attr_vals: row.attr_vals.join(' ') 
        })
        console.log(res);
        if (res.meta.status != 200) return ElMessage.error(res.meta.msg)
        ElMessage.success(res.meta.msg)
        editDialogVisible.value = false
        row = res.data 
    }
    function handleClosed(index, row) {
        row.attr_vals.splice(index, 1)
        uploadData(row)
    }
    // #endregion

</script>
<style scoped lang="scss">
    .cat_opt {
        margin: 15px 0;
        line-height: 33px;
    }

    :deep(.el-cascader) {
        width: 240px;
    }

    .addBtn {
        float: left;
        margin-bottom: 10px;
    }

    .el-tag {
        margin: 5px 10px;
    }

    .button-new-tag {
        margin: 5px 10px;
        height: 32px;
        line-height: 30px;
        padding-top: 0;
        padding-bottom: 0;
    }

    .input-new-tag {
        width: 90px;
        margin: 5px 10px;
        vertical-align: bottom;
    }
</style>